<template>
	<view class="location">
		<uni-popup ref="popup" type="bottom" class="popBox" background-color="none" :is-mask-click="false">
			<view class="topBox">
				<view class="" @click="goBack">返回</view>
				<view class="title">地址选择</view>
				<view class=""></view>
			</view>
			<view class="search-box">
				<text class="flex ai-center">{{ city || "定位中..." }}</text>
				<view class="inputBox flex">
					<m-icon type="icon-sousuo" gap="0 16 0 6"></m-icon>
					<input type="text" placeholder="输入关键字搜素" v-model="search_key" @input="keySearch()">
					<m-icon type="icon-shanchu1" gap="10" v-if="search_key" @click="search_key = ''"></m-icon>
				</view>
			</view>
			<view class="con-box flex-column">
				<!-- 地图 -->
				<view class="mapBox">
					<view class="map" :init-map="initMap" id="mapContainer" :center="center"
						:change:center="AMapInstance.setLocation" />
					<view class="sign" :class="{ 'sign--move': move }">
						<image :src="imgUrl" mode=""></image>
					</view>
					<view class="map_center" :class="{ 'map_center--move': move }">

					</view>
				</view>

				<!-- 附近点 -->
				<view class="list-box pt-24">
					<view class="flex-column plr-24">
						<view class="flex-between ptb-20 border-bottom" v-for="(item, index) in lists" :key="index"
							@click="onResLi(item)">
							<m-icon v-if="index == 0" type="icon-dizhi2" color="#e62626"></m-icon>
							<m-icon v-else type="icon-danxuanweixuanzhong" color="#999"></m-icon>
							<view class="flex-1 flex-between">
								<view class="flex-1 flex-column pl-16">
									<text class="fs28 fw-600">{{ item.name }}</text>
									<text class="fs25 mt-8 text-dark">{{ item.address }}</text>
								</view>
								<text class="text-grey fs26"
									v-if="item.distance1">{{ item.distance1 | integer(2) }}m</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 搜索列表 -->
			<view class="search-list" v-if="false">
				<view class="" v-for="(item, index) in lists" :key="index" @click="onResLi(item)">
					<text>{{ item.name }}</text>
					<text>{{ item.address }}</text>
				</view>
			</view>
		</uni-popup>
	</view>

</template>

<script>
	import qqmapsdk from '@/js_sdk/qqmap-wx-jssdk.js'
	const QQMapWX = new qqmapsdk({ key: 'X2RBZ-OLACB-A5WUZ-J4OK5-QMBDH-5QFNE' });
	export default {
		name: 'location',
		props: {
			markers: {
				type: Object,
				default: () => ({}),
			},
			// center: { // 中心点坐标
			// 	type: Array,
			// 	default: () => [],
			// },
			location: { // 定位坐标
				type: Array,
				default: () => [],
			},
			mapCover: {
				type: Array,
				default: () => [],
			},
			zoom: {
				type: Number,
				default: 10,
			},
		},
		data() {
			return {
				imgUrl: require("../../static/images/default/position2.png"),
				move: false,
				center: [],
				initMap: true,
				city: "",
				search_key: '',
				map: null,
				show: false, // 通过这个属性，控制是否移除dom元素
				lists: [], //地点列表
				search_list: [], //搜索结果列表
			};
		},
		mounted() {
			this.openUp();
		},
		methods: {
			moveFn(val) {
				this.move = val;
			},
			onResLi(item) {
				console.log('item===>', item)
			},
			getLists(lists) {
				this.lists = lists
			},
			cityInfo(val) {
				console.log('cityInfo', val);
				this.city = val.city;
				// this.center = [106.5485535, 29.5549124]
				// this.center = [val.bounds[0], val.bounds[1]]
			},
			openUp() {
				this.$refs.popup.open()
			},

			goBack() {
				// #ifdef H5
				delete(window.AMap);
				// #endif
				this.$emit('show', false);
				console.log("window===>", window);
				this.$refs.popup.close()
			},
			keySearch() {

			},
		}
	}
</script>
<script module="AMapInstance" lang="renderjs">
	export default {
		data() {
			return {
				mCenter: [106.5485535, 29.5549124],
				mCity: '',
				map: null,
				point: '../../static/images/default/position2.png',
			};
		},
		mounted() {
			console.log("window.AMap！", window.AMap);
			// if (window.AMap) return this.initAmap();
			const script = document.createElement('script');
			const securityJsCode = 'f1b946e6f51b1235374f1f92c38b0c33'; //您申请的安全密钥
			const key = 'b0c8fc70cd402ddb153c3416e9261d50'; //您申请的key值
			window._AMapSecurityConfig = {
				securityJsCode: securityJsCode,
			}
			script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}&plugin=AMap.CitySearch`;
			script.onload = () => {
				this.showCityInfo()
				// this.getLocation();
			}
			document.head.appendChild(script);
		},
		methods: {
			//获取用户所在城市信息
			showCityInfo() {
				console.log('获取用户所在城市信息--start')
				var citysearch = new AMap.CitySearch();
				citysearch.getLocalCity((status, result) => {
					console.log("获取用户所在城市信息===>", result);
					if (status === "complete" && result.info === "OK") {
						if (result && result.city && result.bounds) {
							const a = result.rectangle.replace(';', ',').split(',');
							const lng = (Number(a[0]) + Number(a[2])) / 2;
							const lat = (Number(a[1]) + Number(a[3])) / 2;

							this.mCity = result.city;
							this.mCenter = [lng, lat];
							this.getLocation()
							// this.initAmap([lng,lat])
							// this.map.setCity(result.city, result => {
							// 	console.log("setCity===>", result);
							// 	this.map.setZoom(15);
							// 	// this.setLocation(result)
							// })

						}
					} else {
						console.log("获取用户所在城市信息err===>", result);
					}
				});
			},
			// 初始化地图
			initAmap(center) {
				this.map = new AMap.Map('mapContainer', {
					zoom: 15, //显示的缩放级别
					zooms: [2, 30], //地图显示的缩放级别范围, 默认为 [2, 20] ，取值范围 [2 ~ 30]
					center: center || this.mCenter,
				});
				this.map.on("complete", () => {
					console.log("地图加载完成！");
					this.$ownerInstance.callMethod('cityInfo', { city: this.mCity });
					if (!center) {
						this.map.setCity(this.mCity, result => {
							console.log("setCity===>", result);
							this.map.setZoom(15);
							this.setLocation(result);
							this.centerSearch(result)
						})
					} else {
						this.setLocation(center || this.mCenter);
						this.centerSearch(center || this.mCenter)
					}
					let mousedownFun = e => {
						console.log("鼠标在地图上单击按下 ");
						this.move = true;
					};
					let mouseupFun = e => {
						console.log("鼠标在地图上单击抬起 ");
						this.$ownerInstance.callMethod('moveFn', false);
						let currentCenter = map.getCenter();
						this.center = [currentCenter.lng, currentCenter.lat];
						this.centerSearch();
					};
					this.map.on("mousedown", () => {
						this.move = true;
						console.log("鼠标在地图上单击按下 ");
					});
					this.map.on("mouseup", () => {
						console.log("鼠标在地图上单击抬起 ");
					});
					this.map.on("zoomstart", () => {
						console.log("1 ");
					});
					this.map.on("zoomend", () => {
						console.log("2 ");
					});
					this.map.on("touchstart", () => {
						console.log("3 ");
						this.$ownerInstance.callMethod('moveFn', true);
					});
					this.map.on("touchend", () => {
						console.log("4 ");
						let currentCenter = this.map.getCenter();
						this.mCenter = [currentCenter.lng, currentCenter.lat];
						this.centerSearch(this.mCenter)
						this.$ownerInstance.callMethod('moveFn', false);
					});
				});
			},
			// 获取定位
			getLocation() {
				console.log("获取定位--start");
				AMap.plugin(["AMap.Geolocation"], () => {
					const geolocation = new AMap.Geolocation({
						enableHighAccuracy: true, // 是否使用高精度定位，默认：true
						timeout: 2000, // 设置定位超时时间，默认：无穷大
						offset: [10, 20], // 定位按钮的停靠位置的偏移量
						zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
						position: "RB" //  定位按钮的排放位置,  RB表示右下
					});
					geolocation.getCurrentPosition((status, result) => {
						let center = [];
						if (status == "complete") {
							console.log("获取定位成功==>", result);
							center = [result.position.lng, result.position.lat];
							this.initAmap(center)
						} else {
							this.initAmap()
							console.log("获取定位失败==>", result);
							// this.showCityInfo();
							this.Toast("定位失败或没开启定位权限");
						}
					});
				});
			},


			// 根据中心点查询附近地点
			centerSearch(longitude, latitude) {
				console.log("根据中心点查询附近地点");
				AMap.plugin(["AMap.PlaceSearch"], () => {
					//构造地点查询类
					let placeSearch = new AMap.PlaceSearch({
						type: "住宅小区|商务住宅|住宅区|诊所|医疗保健服务|汽车服务|餐饮服务|购物服务|生活服务|体育休闲服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|地名地址信息", // 兴趣点类别
						pageSize: 30, // 单页显示结果条数
						pageIndex: 1, // 页码
						citylimit: true, //是否强制限制在设置的城市内搜索
						city: "全国", // 兴趣点城市
						autoFitView: false // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
					});
					//根据地图中心点查附近地点
					placeSearch.searchNearBy("", [longitude, latitude], 100, (status, result) => {
						console.log("附近点===>", result);
						if (status == "complete") {
							let lists = result.poiList.pois; //将查询到的地点赋值
							// 计算距离
							let pointA = [longitude, latitude];
							let newArr = [];
							lists.forEach(item => {
								let pointB = [item.location.lng, item.location
									.lat
								]; //从数据库中取出商家的经纬度;
								const distance = AMap.GeometryUtil.distance(pointA, pointB);
								item.distance1 = distance;
								newArr.push(item);
							});
							this.$ownerInstance.callMethod('getLists', newArr)
							// this.lists = newArr;
						}
					});
				});
			},

			// setCity(newValue, oldValue, ownerVm, vm) {
			// 	this.map.setCity(this.city, result => {
			// 		console.log("status, result----", result);
			// 		//获取初始中心点并赋值
			// 		// let currentCenter = map.getCenter(); //此方法是获取当前地图的中心点
			// 		// console.log("currentCenter===>", currentCenter);
			// 		this.center = result; //将获取到的中心点的纬度经度赋值给data的center
			// 		//根据地图中心点查附近地点，此方法在下方
			// 		// this.centerSearch();
			// 	});
			// },
			// setCenter(newValue, oldValue, ownerVm, vm) {
			// 	console.log("newValue, oldValue, ===>", newValue, oldValue, );
			// 	if (!this.map) return;
			// 	if (!newValue || newValue.length === 0) return;
			// 	const position = new AMap.LngLat(newValue[0], newValue[1]); // 标准写法
			// 	// 简写 var position = [116, 39];
			// 	this.map && this.map.setCenter(position);
			// 	// this.setMarker()
			// },
			// 设置中心点
			setLocation(newValue, oldValue, ownerVm, vm) {
				console.log("setLocation===>", newValue);
				if (!newValue || newValue.length === 0) return;
				const position = new AMap.LngLat(newValue[0], newValue[1]); // 标准写法
				this.map && this.map.setCenter(position);
				// this.setMarker()
				const wh = this.getWH(68, 56, 32);
				const mark = new AMap.Marker({
					position: position,
					icon: new AMap.Icon({
						image: this.point,
						size: new AMap.Size(wh[0], wh[1]),
						imageSize: new AMap.Size(
							wh[0], wh[1])
					}),
					offset: new AMap.Pixel(-wh[0] / 2, -wh[1]),
					autoRotation: true,
					angle: 0
				});
				this.map.add(mark);

			},
			// 根据坐标查询地址
			getAddressBylanglat(lnglat) {
				let geocoder = new AMap.Geocoder({
					city: "全国", //城市设为北京，默认：“全国”
					radius: 1000 //范围，默认：500
				});
				geocoder.getAddress(lnglat, function(status, result) {
					if (status === 'complete' && result.regeocode) {
						const address = result.regeocode.formattedAddress;
						console.log("getAddress===>", address);
					} else {
						log.error('根据经纬度查询地址失败')
					}
				});
			},
			// 设置标记点
			setMarker() {
				console.log("设置标记点===>", this.map.getCenter());
				let marker = new AMap.Marker({
					position: this.map.getCenter(),
					icon: this.point,
					anchor: 'bottom-center',
					offset: new AMap.Pixel(0, 0)
				});
				marker.setMap(this.map);
			},
			// 根据需要,通过原始宽高和结果宽度，获取结果图片的大小
			getWH(ow, oh, rw) {
				return [rw, rw * oh / ow];
			},
		},
		beforeDestroy() {
			console.log("销毁地图");
			this.map.destroy();
		},
	}
</script>
<style lang="scss">
	.locationBox {
		z-index: 999;
		background-color: rgba(0, 0, 0, 0.2);
	}

	.popBox {
		::v-deep .uni-popup__wrapper {
			height: 85vh;
			display: flex;
			display: -o-flex;
			display: -ms-flex;
			display: -moz-flex;
			display: -webkit-flex;
			flex-direction: column;
		}
	}

	.topBox {
		border-top-left-radius: 40rpx;
		border-top-right-radius: 40rpx;
		overflow: hidden;
		height: 100rpx;
		line-height: 100rpx;
		background-color: #f7f7f7;
		display: grid;
		padding: 0rpx 40rpx;
		grid-template-columns: 200rpx auto 200rpx;

		.title {
			font-size: 30rpx;
			text-align: center;
		}
	}

	.search-box {
		background-color: #fff;
		display: grid;
		padding: 16rpx 30rpx;
		grid-template-columns: 120rpx auto;

		&>text {
			font-size: 26rpx;
		}

		.inputBox {
			background-color: #ededed;
			padding: 0px 20rpx;
			border-radius: 40rpx;

			input {
				padding: 20rpx 0rpx;
				flex: 1;
				font-size: 24rpx;
			}
		}
	}

	.con-box {
		background-color: #fff;
		flex: 1;

		.mapBox {
			position: relative;
			background-color: #fff;
			flex: 1;

			.map {
				width: 100%;
				height: 100%;

				::v-deep .amap-logo {
					bottom: 40rpx !important;
				}

				::v-deep .amap-copyright {
					display: none !important;
					bottom: 36rpx !important;
				}
			}

			.sign {
				top: 50%;
				left: 50%;
				position: absolute;
				transition: all 100ms linear;
				transform: translate(-50%, -28rpx);

				image {
					position: relative;
					top: -30rpx;
					width: 50rpx;
					height: 50rpx;
				}
			}

			.sign--move {
				transform: translate(-50%, -36rpx);
			}

			.map_center {
				display: inline-block;
				position: absolute;
				left: 50%;
				top: calc(50% - 10rpx);
				width: 30rpx;
				height: 15rpx;
				background-color: transparent;
				background-image: url("https://gw.alicdn.com/tfs/TB1AJS.wxD1gK0jSZFyXXciOVXa-36-18.png");
				background-repeat: no-repeat;
				background-position: center center;
				background-size: cover;
				transition: all 100ms linear;
				transform: translateX(-50%);
			}

			.map_center--move {
				transform: translateX(-50%) scale(2) !important;
			}

			.map_center-icon {
				position: absolute;
				top: 0;
				left: 50%;
				width: 60rpx;
				height: 99rpx;
				background-color: transparent;
				background-image: url("https://gw.alicdn.com/tfs/TB1SRe4wxD1gK0jSZFsXXbldVXa-60-99.png");
				background-repeat: no-repeat;
				background-position: center center;
				background-size: cover;
				transition: all 100ms linear;
				transform: translate(-50%, 4.40625rem);
			}

			.map_center-icon--move {
				transform: translate(-50%, 4.09375rem);
			}
		}

		.list-box {
			height: 500rpx;
			position: relative;
			top: -30rpx;
			border-top-left-radius: 30rpx;
			border-top-right-radius: 30rpx;
			background-color: #fff;
			// height: 40%;
			overflow: hidden;

			&>view {
				height: 100%;
				overflow: auto;
			}
		}
	}
</style>